<template>
  <div class="address-container">
    <!-- 左侧侧边栏 -->
    <div class="sidebar">
      <PersonalCenterSidebar />
    </div>

    <!-- 右侧内容区域 -->
    <div class="content-area">
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table :data="tableData" border style="width: 100%">
          <!-- 添加选择列 -->
          <el-table-column
              label="选择"
              width="50"
              align="center"
          >
            <template #default="scope">
              <el-checkbox v-model="scope.row.selected"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="productId" label="产品ID" />
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="storeName" label="商家名称" />
          <el-table-column prop="price" label="价格" />
          <el-table-column
              label="商品图片"
              width="120"
              align="center"
          >
            <template #default="scope">
              <img :src="getImageUrl(scope.row.imageUrl)" alt="商品图片" style="max-width: 100%; max-height: 100px;">
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)">选择数量</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 按钮容器 -->
      <div class="button-container">
        <el-button type="primary" @click="addSelectedItems">生成订单</el-button>
        <el-button type="primary" @click="goBack">返回</el-button>
        <el-button type="success" @click="calculateTotal">计算总价</el-button>
      </div>

      <!-- 已选商品总价显示 -->
      <div class="total-price">已选商品总价：¥<span id="totalPrice">0</span></div>

      <!-- 点击新增，弹出的对话框 -->
      <el-dialog
          v-model="dialogVisible"
          title="提示"
          width="30%"
      >
        <el-form :model="form" label-width="120px">
          <el-form-item label="产品ID">
            <el-input v-model="form.productId" style="width: 80%" />
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="form.productName" style="width: 80%" />
          </el-form-item>
          <el-form-item label="数量">
            <div style="display: flex; align-items: center;">
              <el-button type="primary" icon="el-icon-minus" circle @click="decreaseQuantity"></el-button>
              <el-input v-model.number="form.quantity" style="width: 60px; margin: 0 10px;" readonly></el-input>
              <el-button type="primary" icon="el-icon-plus" circle @click="increaseQuantity"></el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="danger" @click="save">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import router from "@/router"; // 引入路由实例
import PersonalCenterSidebar from "@/views/PersonalCenterSidebar.vue";

export default {
  name: 'Home',
  components: {PersonalCenterSidebar},
  data() {
    return {
      form: {
        quantity: 1 // 默认数量为1
      },
      dialogVisible: false,
      search: '',
      currentPage: 1,
      total: 10,
      pageSize: 5,
      tableData: [],
      userNameQuery: ''
    }
  },
  methods: {
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    handleSizeChange() {
      this.load();
    },
    handleCurrentChange() {
      this.load();
    },
    addSelectedItems() {
      const selectedItems = this.tableData.filter(item => item.selected);
      if (selectedItems.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择要新增的商品"
        });
        return;
      }

      selectedItems.forEach(item => {
        request.post("/user/createOrder", item).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
            this.$router.push('/UserOrder')
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: "error",
            message: "新增失败：" + err.message
          })
        });
      });

      // 清空选中状态
      this.tableData.forEach(item => item.selected = false);

      // 刷新表格数据
      this.load();
    },
    save() {
      if (this.form.id) {
        request.put("/user/updateProductQuantity", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "添加成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load();
          this.dialogVisible = false;
        })
      } else {
        request.post("/user/createOrder", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "即将支付"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load();
          this.dialogVisible = false;
        })
      }
    },
    load() {
      request.get("/user/cartSelectPage", {
        params: {
          pageNumber: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        this.tableData = res.data.list.map(item => ({ ...item, selected: false }));
        this.total = res.data.total;
      })
    },
    searchByRoomName() {
      request.get("/user/getUseByName", {
        params: {
          username: this.userNameQuery
        }
      }).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
      });
    },
    getImageUrl(imagePath) {
      return imagePath.startsWith('http') ? imagePath : require(`@/${imagePath}`);
    },
    goBack() {
      router.go(-1);
    },
    calculateTotal() {
      let totalPrice = 0;
      this.tableData.forEach((item) => {
        if (item.selected) {
          totalPrice += item.price * item.quantity;
        }
      });
      document.getElementById('totalPrice').innerText = totalPrice;
      this.$message({
        type: 'success',
        message: `选中商品总价为：${totalPrice}`
      });
    },
    increaseQuantity() {
      this.form.quantity++;
    },
    decreaseQuantity() {
      if (this.form.quantity > 1) {
        this.form.quantity--;
      }
    }
  },
  created() {
    this.load();
  }
}
</script>

<style scoped>
/* 容器样式 */
.address-container {
  display: flex;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 1000px;
  margin: 0 auto;
}

/* 左侧侧边栏样式 */
.sidebar {
  width: 250px;
  margin-right: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 右侧内容区域样式 */
.content-area {
  flex-grow: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 表格容器样式 */
.table-container {
  margin-bottom: 20px;
}

/* 按钮容器样式 */
.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 按钮样式 */
.el-button {
  margin: 0 5px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: scale(1.05);
}

/* 输入框样式 */
.el-input {
  transition: border-color 0.3s;
}

.el-input:focus-within {
  border-color: #409eff;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-dialog__header {
  background-color: #f0f0f0;
  padding: 15px;
  border-bottom: 1px solid #ddd;
  border-radius: 10px 10px 0 0;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px;
  border-top: 1px solid #ddd;
  border-radius: 0 0 10px 10px;
  text-align: right;
}

/* 总价显示区域样式 */
.total-price {
  font-size: 18px;
  color: #333;
  margin: 20px 0;
  text-align: center;
}
</style>